<?php

/**
 * Manage ad
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class AdController extends Controller {

    public function filters() {
	return array(
	    'accessControl'    // required to enable accessRules
	);
    }

    public function accessRules() {
	return array(
	    array('allow', // allow all users to perform 'index' and 'view' actions
		'actions' => array('index', 'view', 'search', 'type', 'vendor'),
		'users' => array('*'),
	    ),
	    array('allow',
		'actions' => array(
		    'register', 'reportabuse', 're_active', 'save_agree'
		),
		'users' => array('@')
	    ),
	    array('deny', // deny everybody else
		'users' => array('*')
	    )
	);
    }

    public function actionRegister($type = 'equipment') {

	//switch type to bind model
	$params = array();

	switch ($type) {
	    case 'equipment':
		$model = new Equipment();
		break;
	    case "supply":
		$model = new Supply();
		break;
	    case 'resume' :
		$model = new Resume();
		break;
	    case 'job' :
		$model = new Job;
		break;

	    case 'vendor':
		$model = new Vendor();
		$params['eblast'] = new Eblast();
		break;
	    case 'technical':
		$model = new Technical();
		$params['eblast'] = new Eblast();
		break;
	    case 'advertise':
		$model = new Advertise();
		break;
	    default :
		$model = new Equipment();
		break;
	}

	$model->contact_country = "US";
	if (r()->isPostRequest) {

	    $price = false;
	    switch ($type) {
		case 'equipment':
		    $price = $this->_registerEquipment($model);
		    break;
		case "supply":
		    $price = $this->_registerSupply($model);
		    break;
		case 'resume' :
		    $model->resume_builder = serialize($_POST['ResumeBuilder']);
		    $price = $this->_registerResume($model);
		    break;
		case 'job' :
		    $price = $this->_registerJob($model);
		    break;

		case 'vendor':
		    $price = $this->_registerCompanySource($model, $params['eblast'], 'Vendor');
		    break;
		case 'technical':
		    $price = $this->_registerCompanySource($model, $params['eblast'], 'Technical');
		    break;
		case 'advertise':
		    $price = $this->_registerAdvertise($model);
		    break;
		default :
		    $price = $this->_registerEquipment($model);
		    break;
	    }

	    if ($price !== false) {
		unset(Yii::app()->session['agree']);
		$params = array(
		    'duration' => isset($_POST['duration']) ? $_POST['duration'] : 0
		);

		//redirect to paypal
		$this->_redirectPaypal($model, $price, $params);
	    }
	}

	$this->render('register', array(
	    'model' => $model,
	    'params' => $params
	));
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerEquipment($model) {

	$model->attributes = $_POST['Equipment'];
	$model->status = Ad::STATUS_PENDING;
	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {
	    $model->image = UploadHelper::saveImage($fileHandler);
	}

	if ($model->validate()) {
	    if ($model->save()) {
		//cal price
		$totalPrice = 0;
		$totalPrice += Category::getPrice($model->main_category, $_POST['duration']);
		$numCatChoose = 0;
		$finalCatPrice = 0;
		$totalPriceCat = 0;
		//check other categoris
		if (!empty($model->otherCategoryIds)) {
		    foreach ($model->otherCategoryIds as $catId) {
			$totalPriceCat += Category::getPrice($catId, 'price_addition');
			$numCatChoose += 1;
		    }
		}
		if ($numCatChoose > 1) {//if choose more 2 categories
		    $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
		} else {
		    $finalCatPrice = $totalPriceCat;
		}
		$totalPrice += $finalCatPrice;
		return $totalPrice;
	    }
	}

	return false;
    }

    /**
     *
     * @param Supply $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerSupply($model) {
	$model->attributes = $_POST['Supply'];
	$model->status = Ad::STATUS_PENDING;

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {
	    $model->image = UploadHelper::saveImage($fileHandler);
	}

	if ($model->validate()) {
	    if ($model->save()) {
		//cal price
		$totalPrice = 0;
		$totalPrice += Category::getPrice($model->main_category, $_POST['duration']);

		$numCatChoose = 0;
		$finalCatPrice = 0;
		$totalPriceCat = 0;
		//check other categoris
		if (!empty($model->otherCategoryIds)) {
		    foreach ($model->otherCategoryIds as $catId) {
			$totalPriceCat += Category::getPrice($catId, 'price_addition');
			$numCatChoose += 1;
		    }
		}
		if ($numCatChoose > 1) {//if choose more 2 categories
		    $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
		} else {
		    $finalCatPrice = $totalPriceCat;
		}
		$totalPrice += $finalCatPrice;
		return $totalPrice;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerCompanySource($model, $eblast, $postType) {
	$model->attributes = $_POST[$postType];
	$model->status = Ad::STATUS_PENDING;
	$aEblast = array();
	$error = '';
	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {
	    $model->image = UploadHelper::saveImage($fileHandler);
	}
	if (isset($_POST[$postType]['featured'])) {
	    //check whether there is 6 feature
	    $numFeature = CompanySource::getAllFeature();
	    if ($numFeature['num_featured'] >= 6) {
		Yii::app()->user->setFlash('featureOverLimit', '<div class="alert alert-block alert-error">There are 6 featured ads still haven\'t expired yet
		    <br/>You need to wait until <strong>' . date('d-m-Y', $numFeature['min_expire'] + 24 * 3600) . '</strong> to post featured ads again.');
		$error = 1;
	    }

	    //save advertisement image
	    if (($fileHandler = CUploadedFile::getInstance($model, 'advertisement'))) {
		$model->advertisement = UploadHelper::saveImage($fileHandler, 'feature');
	    }
	}
	if (isset($_POST['eblast'])) {
	    //save advertisement image
	    if (($fileHandler = CUploadedFile::getInstance($eblast, 'advertisement'))) {
		$eblastFile = UploadHelper::saveDocument($fileHandler, 'eblast');
	    }
	}
	if ($model->validate()) {
	    $flag = true;
	    //eblast validate
	    if (isset($_POST['eblast'])) {
		$eblast->attributes = $_POST['Eblast'];

		if (!$eblast->validate()) {
		    $flag = false;
		} else {
		    if (strtotime($_POST['Eblast']['start_date']) < strtotime('+5 days')) {

			$error = 1;
			Yii::app()->user->setFlash('eblastTimeError', '<div class="alert alert-block alert-error"><strong>Eblast Error: </strong>
			    Please pick date after ' . date('d-m-Y', strtotime('+5 days')) . '. This will give us the opportunity to check the ad before we send it.</div>');
		    } else {
			$aEblast = $_POST['Eblast'];
			if (isset($eblastFile)) {
			    $aEblast['advertisement'] = $eblastFile;
			}
			$model->eblast = $aEblast;
		    }
		}
	    }

	    if ($flag && !$error) {

		if ($model->save()) {

		    //cal price
		    $totalPrice = 0;
		    $totalPrice += Category::getPrice($model->main_category, $_POST['duration']);

		    $numCatChoose = 0;
		    $finalCatPrice = 0;
		    $totalPriceCat = 0;

		    if ($postType == "Technical") {
			//check other categories
			if (!empty($model->otherCategoryIds)) {
			    foreach ($model->otherCategoryIds as $catId) {
				$totalPriceCat += Category::getPrice($catId, 'price_addition');
				$numCatChoose += 1;
			    }
			}
			if ($numCatChoose > 1) {//if choose more 2 categories
			    $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
			} else {
			    $finalCatPrice = $totalPriceCat;
			}
			$totalPrice += $finalCatPrice;
		    }
		    //if user choose e-blast
		    if (isset($_POST['eblast']) && $_POST['eblast']) {
			$totalPrice += Category::getPrice($eblast->main_category, 'price_e_blast');

			$numCatChooseEblast = 0;
			$finalCatPriceEblast = 0;
			$totalPriceCatEblast = 0;
			//check other categories
			if (!empty($eblast->otherCategoryIds)) {
			    foreach ($eblast->otherCategoryIds as $catId) {
				$totalPriceCatEblast += Category::getPrice($catId, 'price_addition');
				$numCatChooseEblast += 1;
			    }
			}
			if ($numCatChooseEblast > 1) {//if choose more 2 categories
			    $finalCatPriceEblast = $totalPriceCatEblast - $totalPriceCatEblast * (floatval(settings()->get('discount', 'discount_category')) / 100);
			} else {
			    $finalCatPriceEblast = $totalPriceCatEblast;
			}
			$totalPrice += $finalCatPriceEblast;
		    }

		    //if user choose featured
		    if (($_POST[$postType]['featured'])) {
			$totalPrice += floatval(settings()->get('post_price', 'featured'));
		    }
		    return $totalPrice;
		}
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerJob($model) {
	$model->attributes = $_POST['Job'];
	$model->status = Ad::STATUS_PENDING;
	$model->title = 'Job';

	if ($model->validate()) {
	    if ($model->save()) {
		//cal price
		$totalPrice = 0;
		$totalPrice += Category::getPrice($model->main_category, $_POST['duration']);
		/**
		  $numCatChoose = 0;
		  $finalCatPrice = 0;
		  $totalPriceCat = 0;
		  //check other categories
		  if (!empty($model->otherCategoryIds)) {
		  foreach ($model->otherCategoryIds as $catId) {
		  $totalPriceCat += Category::getPrice($catId, 'price_addition');
		  $numCatChoose += 1;
		  }
		  }
		  if ($numCatChoose > 1) {//if choose more 2 categories
		  $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
		  } else {
		  $finalCatPrice = $totalPriceCat;
		  }
		  $totalPrice += $finalCatPrice;
		 * 
		 */
		return $totalPrice;
	    }
	}

	return false;
    }

    /**
     *
     * @param Equipment $model
     * @return mixed false if save false, total price if save successfully
     */
    private function _registerResume($model) {
	$model->attributes = $_POST['Resume'];

	$model->status = Ad::STATUS_PENDING;
	$model->title = 'Resume';

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'resume'))) {
	    $model->resume = UploadHelper::saveDocument($fileHandler);
	}

	if ($model->validate()) {
	    if ($model->save()) {
		$totalPrice = 0;
		$totalPrice = floatval(settings()->get("post_price", "resume"));
		/*
		  $numCatChoose = 0;
		  $finalCatPrice = 0;
		  $totalPriceCat = 0;

		  //check other categories
		  if (!empty($model->otherCategoryIds)) {
		  foreach ($model->otherCategoryIds as $catId) {
		  $totalPriceCat += Category::getPrice($catId, 'price_addition');
		  $numCatChoose += 1;
		  }
		  }
		  if ($numCatChoose > 1) {//if choose more 2 categories
		  $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
		  } else {
		  $finalCatPrice = $totalPriceCat;
		  }
		  $totalPrice += $finalCatPrice;
		 */
		return $totalPrice;
	    }
	}

	return false;
    }

    /*
     * 
     */

    private function _registerAdvertise($model) {
	$model->attributes = $_POST['Advertise'];
	$model->status = Ad::STATUS_PENDING;

	//save image
	if (($fileHandler = CUploadedFile::getInstance($model, 'image'))) {
	    $model->image = UploadHelper::saveImage($fileHandler);
	}


	if ($model->validate()) {
	    if ($model->save()) {
		//cal price
		$totalPrice = 0;
		$totalPrice += Category::getPrice($model->main_category, $_POST['duration']);
		$numCatChoose = 0;
		$finalCatPrice = 0;
		$totalPriceCat = 0;
		//check other categoris
		if (!empty($model->otherCategoryIds)) {
		    foreach ($model->otherCategoryIds as $catId) {
			$totalPriceCat += Category::getPrice($catId, 'price_addition');
			$numCatChoose += 1;
		    }
		}
		if ($numCatChoose > 1) {//if choose more 2 categories
		    $finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
		} else {
		    $finalCatPrice = $totalPriceCat;
		}
		$totalPrice += $finalCatPrice;
		return $totalPrice;
	    }
	}

	return false;
    }

    /**
     *
     */
    private function _redirectPaypal($model, $price, $params = array()) {
	$paymentInfo = array();
	$paymentInfo['Order']['theTotal'] = $price;
	$paymentInfo['Order']['description'] = 'Register an ad';
	$paymentInfo['Order']['quantity'] = '1';

	// call paypal
	$result = Yii::app()->Paypal->SetExpressCheckout($paymentInfo);
	//Detect Errors
	if (!Yii::app()->Paypal->isCallSucceeded($result)) {
	    if (Yii::app()->Paypal->apiLive === true) {
		//Live mode basic error message
		$error = 'We were unable to process your request. Please try again later';
	    } else {
		//Sandbox output the actual error message to dive in.
		$error = $result['L_LONGMESSAGE0'];
	    }
	    echo $error;
	    Yii::app()->end();
	} else {
	    // send user to paypal
	    $token = urldecode($result["TOKEN"]);
	    $payPalURL = Yii::app()->Paypal->paypalUrl . $token;

	    //add new invoice
	    $invoice = new Invoice;
	    $invoice->attributes = array(
		'model' => Invoice::MODEL_AD,
		'model_id' => $model->ad_id,
		'payment_method' => 'paypal',
		'payment_code' => $token,
		'status' => Invoice::STATUS_PENDING,
		'params' => CJSON::encode($params),
		'create_by' => user()->id,
		'total' => $price
	    );

	    if ($invoice->save()) {
		$this->redirect($payPalURL);
	    } else {
		die('An error occured, please try again!');
	    }
	}
    }

    /**
     * show archive ads
     */
    public function actionIndex() {
	//get latest ad
	$criteria = new CDbCriteria();
	$criteria->addCondition('type NOT IN( ' . Ad::TYPE_TECHNICAL . ', ' . Ad::TYPE_VENDOR . ') AND status = ' . Ad::STATUS_APPROVE);
	//order by last update
	$criteria->order = 'updated DESC';

	$dataProvider = new CActiveDataProvider('Ad', array(
	    'criteria' => $criteria
	));


	//get feature ad
	$featureAds = Ad::model()->findAll(array(
	    'condition' => '`featured` = 1 and `status` = ' . Ad::STATUS_APPROVE . ' and expire_featured >' . time(),
	    'limit' => 10
	));

	$this->render('index', array(
	    'dataProvider' => $dataProvider,
	    'featureAds' => $featureAds
	));
    }

    /**
     * show archive ads
     */
    public function actionSearch() {
	switch ($_GET['type']) {
	    case 'equipment' :
		$type = Ad::TYPE_EQUIPMENT;
		break;
	    case 'supplies':
		$type = Ad::TYPE_SUPPLY;
		break;
	    case 'job' :
		$type = Ad::TYPE_JOB;
		break;
	    case 'resume' :
		$type = Ad::TYPE_RESUME;
		break;
	    case 'vendor' :
		$type = Ad::TYPE_VENDOR;
		break;
	    case 'technical' :
		$type = Ad::TYPE_TECHNICAL;
		break;
	    default :
		$type = Ad::TYPE_ADVERTISE;
		break;
	}

	//get latest ad
	$criteria = new CDbCriteria();
	$criteria->select = 't.*';
	$criteria->join = 'JOIN {{ads_categories}} ac ON ac.ad_id = t.ad_id';

	$criteria->addCondition('t.type = ' . $type . ' AND t.status = ' . Ad::STATUS_APPROVE);
	if ($_GET['category']) {
	    $criteria->addCondition('t.main_category = ' . $_GET['category'] . ' OR ac.category_id=' . $_GET['category']);
	}
	if ($_GET['country']) {
	    $criteria->addCondition('t.contact_country = "' . $_GET['country'] . '"');
	}

	if ($_GET['state-search']) {
	    $criteria->compare('t.contact_state', $_GET['state-search'], true);
	}

	//if search in my post
	if (isset($_GET['isMyPost']) && $_GET['isMyPost']) {
	    $criteria->addCondition('t.user_id=' . user()->id);
	}

	$criteria->group = 't.ad_id';
	//order by last update
	$criteria->order = 'updated DESC';

	Ad::model()->count($criteria);

	$dataProvider = new CActiveDataProvider('Ad', array(
	    'criteria' => $criteria
	));


	//get feature ad
	$featureAds = Ad::model()->findAll(array(
	    'condition' => '`featured` = 1 AND status = ' . Ad::STATUS_APPROVE . ' and expire_featured >' . time(),
	    'limit' => 6
	));

	$this->render('index', array(
	    'dataProvider' => $dataProvider,
	    'featureAds' => $featureAds,
	    'search' => '1'
	));
    }

    /**
     * view detail of an ad
     * @param type $id
     * @param type $name
     * @throws CHttpException
     */
    public function actionView($id, $name = '') {
	$model = Ad::model()->with(array('categories', 'mainCategory'))->findByPk($id);
	if (!$model || $model->status != Ad::STATUS_APPROVE) {
	    throw new CHttpException(404, 'Page was not exists');
	}
	$aStatementAbuse = StatementAbuse::getStatement();
	$this->render('view', array(
	    'model' => $model,
	    'aStatementAbuse' => $aStatementAbuse
	));
    }

    /**
     * list ad by type
     * @param type $type
     */
    public function actionType($type = 'equipment') {
	switch ($type) {
	    case 'equipment' : case 'supplies' :
		$type = Ad::TYPE_EQUIPMENT;
		break;
	    case 'vendor' : case 'technical' :
		$type = Ad::TYPE_COMPANY_SOURCE;
		break;
	    case 'job' :
		$type = Ad::TYPE_JOB;
		break;
	    case 'resume' :
		$type = Ad::TYPE_RESUME;
		break;
	    default :
		$type = Ad::TYPE_EQUIPMENT;
		break;
	}

	//get latest ad
	$criteria = new CDbCriteria();
	$criteria->with = "categories";
	$criteria->addCondition('type = ' . $type);
	//order by last update
	$criteria->order = 'updated DESC';

	$dataProvider = new CActiveDataProvider('Ad', array(
	    'criteria' => $criteria
	));


	//get feature ad
	$featureAds = Ad::model()->findAll(array(
	    'condition' => '`featured` = 1 AND status = ' . Ad::STATUS_APPROVE . ' and expire_featured >' . time(),
	    'limit' => 6
	));

	$this->render('index', array(
	    'dataProvider' => $dataProvider,
	    'featureAds' => $featureAds
	));
    }

    /**
     * list company source ads
     */
    public function actionVendor() {
	$criteria = new CDbCriteria();
	$criteria->order = 'updated DESC';
	$criteria->condition = 'type IN( ' . Ad::TYPE_VENDOR . ', ' . Ad::TYPE_TECHNICAL . ') AND status = ' . Ad::STATUS_APPROVE;
	$dataProvider = new CActiveDataProvider('Ad', array(
	    'criteria' => $criteria
	));


//	//get feature ad
//	$featuredModels = CompanySource::model()->findAll();
	//get feature ad
	$featureAds = Ad::model()->findAll(array(
	    'condition' => '`featured` = 1 AND status = ' . Ad::STATUS_APPROVE . ' and expire_featured >' . time(),
	    'limit' => 6
	));
	$this->render('vendor', array(
	    'dataProvider' => $dataProvider,
	    'featureAds' => $featureAds
	));
    }

    /**
     * Report abuse
     */
    public function actionReportAbuse() {

	if (isset($_POST['link']) && isset($_POST['userId']) && isset($_POST['postId']) && isset($_POST['text'])) {
	    $model = new Abuse();
	    $model->link_post = $_POST['link'];
	    $model->user_id = $_POST['userId'];
	    $model->post_id = $_POST['postId'];
	    $model->message = $_POST['text'];
	    $model->time_created = time();
	    if ($model->save()) {
		echo 1;
	    }
	}
    }

    /*
     * Reactive your post
     */

    public function actionRe_active($id) {
	$modelAds = Ad::model()->with('categories')->findByPk($id);

	//get duration of this post
	$model = Invoice::model()->find('model=:model and model_id=:model_id', array(
	    ':model' => Invoice::MODEL_AD,
	    ':model_id' => $id
	));
	$totalPrice = 0;
	if ($model) {
	    $duration = CJSON::decode($model->params);

	    $totalPrice = 0;
	    $totalPrice += Category::getPrice($modelAds->main_category, $duration['duration']);
	    $finalCatPrice = 0;
	    $totalPriceCat = 0;
	    if (!empty($modelAds->categories)) {
		foreach ($modelAds->categories as $catId) {
		    $totalPriceCat += Category::getPrice($catId->category_id, 'price_addition');
		}
	    }
	    if (count($modelAds->categories) > 1) {//if choose more 2 categories
		$finalCatPrice = $totalPriceCat - $totalPriceCat * (floatval(settings()->get('discount', 'discount_category')) / 100);
	    } else {
		$finalCatPrice = $totalPriceCat;
	    }
	    $totalPrice += $finalCatPrice;

	    $params = array(
		'duration' => $duration['duration']
	    );

	    $this->_redirectPaypal($modelAds, $totalPrice, $params);
	} else {
	    throw new CHttpException(404, 'Page was not existed');
	}
    }

    /**
     * save session when register
     */
    public function actionSave_agree() {
	if (isset($_POST['userId'])) {
	    Yii::app()->session['agree'] = $_POST['userId'];
	}
    }

}

